package br.org.group.android.dao;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Text;

public class ImportFortunes {

	public int Popula() {
		int id = 0;
		ArrayList<FortunesDAO> fortunes = new ArrayList<FortunesDAO>();
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream("fortunes_br"), "UTF8"), 1024);
			;
			boolean bfortune = true;
			StringBuffer autor = new StringBuffer();
			StringBuffer mensagem = new StringBuffer();

			while (in.ready()) {

				StringTokenizer partes = new StringTokenizer(in.readLine());
				String aux;

				while (partes.hasMoreTokens()) {

					aux = partes.nextToken();

					if (aux.endsWith("}")) {
						autor.append(aux.replace("{", "").replace("}", ""));

						FortunesDAO fdao = new FortunesDAO(new Text(mensagem
								.toString().trim()), autor.toString().trim());
						fdao.setId((long) ++id);
						fortunes.add(fdao);
						autor.delete(0, autor.length());
						mensagem.delete(0, mensagem.length());

						bfortune = true;

					} else if (bfortune && aux.indexOf("{") == -1) {
						mensagem.append(aux.replace("%", "") + " ");

					} else {
						bfortune = false;

						autor.append(aux.replace("{", "") + " ");
					}

				}

			}

		} catch (IOException e) {
			;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {

			pm.makePersistentAll(fortunes);

		} finally {
			pm.close();
		}
		return id;
	}

}
